package itsm.isperp.framework.utils;

import itsm.isperp.framework.data.dialect.DialectFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.springframework.data.jdbc.support.DatabaseType;

import com.fr.report.web.button.Word;

/**
 * 字符串的辅助方法
 * 
 * @author lizx
 * @date 2013-1-26
 * @version V1.0
 */
public final class StringUtils {

	static char[] a_z = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
			'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
			'x', 'y', 'z' };// "abcdefghijklmnopqrstuvwxyz".toCharArray();

	static char[] A_Z = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
			'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
			'X', 'Y', 'Z' };

	/**
	 * 将 camelCase 转为underscore，delimiterChars 为指定的分隔符，默认为_ <br />
	 * example : loveYou 转为 love_you
	 * 
	 * @param camelCaseWord
	 *            驼峰
	 * @param delimiterChars
	 *            分隔符
	 * @return 下划线分隔字符串
	 */
	public static final String underscore(String camelCaseWord,
			char... delimiterChars) {

		return _underscore(camelCaseWord, delimiterChars).toLowerCase();
	}

	public static final String underscoreForSql(String camelCaseWord,
			char... delimiterChars) {
		String target = _underscore(camelCaseWord, delimiterChars);

		if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {

			return "\"" + target.toUpperCase() + "\"";
		}

		return target.toLowerCase();
	}

	private static final String _underscore(String camelCaseWord,
			char... delimiterChars) {
		if (camelCaseWord == null)
			return null;
		String target = camelCaseWord.trim();
		if (target.length() == 0)
			return "";
		target = target.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2");
		target = target.replaceAll("([a-z\\d])([A-Z])", "$1_$2");
		// target = target.replaceAll("-", "_");
		if (delimiterChars != null) {
			for (char delimiterChar : delimiterChars) {
				target = target.replace(delimiterChar, '_');
			}
		}

		return target;
	}

	/**
	 * 将underscore 转为 camelCase，分隔符为_ <br />
	 * example : love_you 转为 loveYou
	 * 
	 * @param underscoreWord
	 *            下划线字符串
	 * @return 驼峰模式字符串
	 */
	public static final String camelCaseWord(final String underscoreWord) {
		if (underscoreWord == null || underscoreWord.equals("")) {
			return "";
		}
		StringBuilder sb = new StringBuilder(underscoreWord.length());
		// 当前的下标
		int i = 0;
		int length = underscoreWord.length();
		for (int j = 0; j < length; j++) {
			if (underscoreWord.charAt(j) == '_') {

				if (j == (length - 1)) {
					break;
				}

				// 判断后面是否还有_
				while (underscoreWord.charAt(++j) == '_') {
				}
				i = j;// i所对应的字符需要转换为大写字符
				char c = underscoreWord.charAt(i);
				for (int k = 0; k < a_z.length; k++) {
					if (a_z[k] == c) {
						c = A_Z[k];
						break;
					}
				}
				sb.append(c);
			} else {
				sb.append(underscoreWord.charAt(j));
			}
		}

		return sb.toString();
	}

	/**
	 * 清楚带有XSS特征的字符（过滤漏洞），sql注入过滤使用
	 * {@link org.apache.commons.lang.StringEscapeUtils#escapeSql}
	 * 
	 * @param 输入字符串
	 * @return 过滤后字符串
	 */
	public static final String cleanXSS(String input) {
		if (org.apache.commons.lang3.StringUtils.isEmpty(input))
			return input;

		input = input.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
		input = input.replaceAll("\\(", "&#40;").replaceAll("\\)", "&#41;");
		input = input.replaceAll("'", "&#39;");
		input = input.replaceAll("eval\\((.*)\\)", "");
		input = input.replaceAll("[\\\"\\'][\\s]*javascript:(.*)[\\\"\\']",
				"\"\"");
		input = input.replaceAll("script", "");
		return input;

	}

	/**
	 * 分词
	 * 
	 * @param input
	 * @return
	 * @throws JcsegException
	 * @throws IOException
	 */
	public static final List<String> tokenizer(String input) {
		List<Term> list = ToAnalysis.parse(input);

		List<String> data = new ArrayList<>();

		for (Term word : list) {
			data.add(word.getNatureStr());
		}
		return data;
	}

	public static String getPinYin(String src) {
		try {
			src = URLDecoder.decode(src, "utf-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("无法识别的汉字编码！");
		}

		char[] t1 = null;
		t1 = src.toCharArray();
		String[] t2 = new String[t1.length];
		// 设置汉字拼音输出的格式
		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		t3.setVCharType(HanyuPinyinVCharType.WITH_V);
		String t4 = "";
		int t0 = t1.length;
		try {
			for (int i = 0; i < t0; i++) {
				// 判断是否为汉字字符
				if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
					t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 将汉字的几种全拼都存到t2数组中
					t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
				} else {
					// 如果不是汉字字符，直接取出字符并连接到字符串t4后
					t4 += Character.toString(t1[i]);
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			throw new RuntimeException("汉字转化拼音失败！");
		}
		return t4;
	}
}
